package etc.obu.service.impl;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.IntentFilter;
import android.util.Log;

import etc.obu.service.IObuFacade;
import etc.obu.service.IResultHandler;
import etc.obu.service.model.CommonState;
import etc.obu.service.model.ServiceStatus;
import etc.obu.service.utils.GpsUtil;

@SuppressWarnings("all")
public class ObuFacadeImpl implements IObuFacade {
    private String tag=ObuFacadeImpl.class.getName();
    private BluetoothAdapter ble = BluetoothAdapter.getDefaultAdapter();
    //结果处理
    private IResultHandler resultHandler;
    private ScanBroadcastReceiver scanReceiver;
    private ObuMessenger obuMessenger;
    private static ObuFacadeImpl obuFacade;

    private ObuFacadeImpl(IResultHandler resultHandler) {
        this.resultHandler = resultHandler;
        scanReceiver = new ScanBroadcastReceiver(resultHandler);
    }
    public static ObuFacadeImpl getInstance(IResultHandler resultHandler){
        if(obuFacade==null){
            obuFacade=new ObuFacadeImpl(resultHandler);
        }
        return obuFacade;
    }

    public static ObuFacadeImpl getInstance(){
        return obuFacade;
    }

    /**
     * 会扫描12秒
     */
    @Override
    public synchronized void initialize(Activity activity) {
        checkPermission(activity);
        IntentFilter scanFilter = new IntentFilter();
        scanFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
        scanFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        scanFilter.addAction(BluetoothDevice.ACTION_FOUND);
        activity.registerReceiver(scanReceiver, scanFilter);
        Log.i(tag,"准备开启扫描");
        if (!ble.startDiscovery()) {
            resultHandler.onInitialize(ServiceStatus.fail("开启扫描失败，请检查版本是否匹配"));
        }
    }

    @Override
    public synchronized void connectDevice(Activity activity) {
        if (obuMessenger==null||obuMessenger.getState()==CommonState.error) {
            if(obuMessenger!=null){
                obuMessenger.setState(null);
            }
            new Thread(() -> {
                checkPermission(activity);
                Log.i(tag,"准备连接环境");
                long start=System.currentTimeMillis();
                while (true) {
                    if (scanReceiver.getState() == CommonState.finish) {
                        BluetoothDevice obuDevice = scanReceiver.getTargetObu().getBluetoothDevice();
                        obuMessenger = new ObuMessenger(resultHandler, obuDevice);
                        Log.i(tag,"开始连接obu ---> "+obuDevice.getName());
                        obuDevice.connectGatt(activity, false, obuMessenger);
                        break;
                    } else if (scanReceiver.getState() == CommonState.error) {
                        resultHandler.onConnectionDevice(ServiceStatus.fail("未找到可建立连接的obu"));
                        break;
                    }else if(System.currentTimeMillis()-start>20000){
                        resultHandler.onConnectionDevice(ServiceStatus.fail("未找到可建立连接的obu"));
                        break;
                    }
                }
            }).start();
        } else {
            resultHandler.onConnectionDevice(ServiceStatus.fail("已连接obu请勿重复连接"));
        }
    }

    @Override
    public synchronized void  getDeviceInformation() {
        new Thread(()->{
            long start=System.currentTimeMillis();
            while(true){
                if(obuMessenger!=null&&obuMessenger.getState()==CommonState.finish){
                    try {
                        Log.i(tag,"发出获取设备信息指令");
                        obuMessenger.sendMessage("508001018050",IResultHandler.class.getMethod("onGetDeviceInformation", ServiceStatus.class));
                        break;
                    } catch (NoSuchMethodException e) {
                        e.printStackTrace();
                    }
                }else if(obuMessenger!=null&&obuMessenger.getState()==CommonState.error){
                    resultHandler.onGetDeviceInformation(ServiceStatus.fail("设备断开连接，无法发送请重新连接"));
                    break;
                }else if(System.currentTimeMillis()-start>60000){
                    resultHandler.onGetDeviceInformation(ServiceStatus.fail("无法获取信道"));
                    break;
                }
            }
        }).start();
    }


    private void checkPermission(Activity activity) {
        if (!GpsUtil.isOPen(activity)) {
            resultHandler.onInitialize(ServiceStatus.fail("请打开gps"));
            return;
        }
        if (ble.getState() != BluetoothAdapter.STATE_ON) {
            resultHandler.onInitialize(ServiceStatus.fail("请打开蓝牙"));
            return;
        }
    }
}
